const path = require('path');

const express        = require('express');
const router = express.Router();
var request = require('request');
var bodyParser = require('body-parser')

var multer  = require('multer')
var cors = require('cors');

const fse = require('fs-extra') 
const dbq = require('./mysql.js');

router.use(cors())

router.post('/em', bodyParser.urlencoded({ extended: false }), (req, res, next)=>{

    // var filePath = `C:/home/wwwroot/www.talenmall.com/mail/backend/output/em_${new Date().getTime()}.json`
    var filePath = `/home/wwwroot/www.talenmall.com/mail/backend/output/em_${req.body.event}_${new Date().getTime()}.json`;
    fse.outputJsonSync(filePath, req.body);
    
    console.log('new email response: ' + req.body.event);
    if(req.body.event == 'request'){
        res.send({code: 0, opt: 'dismiss'});
    }else if(req.body.event == 'deliver' || req.body.event == 'invalid'){
        handleIt(req, res);
    }else{
        res.send({code: 1, opt: 'none'})
    }
    
});


function handleIt(req, res){
    dbq.getHook2Entry(req.body.emailId)
    .then(results=>{
        dbq.updHook2Entry(req.body.event, req.body.subStatDesc, req.body.emailId)
        .then(results2=>{
            res.send({results2});
        }, err2=>{
            res.send({err2});
            console.error(err2);
        });
    }, err=>{
        res.send({err});
        console.error(err);
    })
}



module.exports = router;